﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class NewBehaviourScript4 : MonoBehaviour
{
    public byte[] data = new byte[10240];
    // Use this for initialization
    

    // Update is called once per frame
    void Update()
    {

    }

    void Start()
    {
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        EndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);



        byte[] dataBuffer = new byte[1024];
        string message = Encoding.UTF8.GetString(dataBuffer, 0, dataBuffer.Length);
        Debug.Log("/" + message + "/");

        try
        {
            clientSocket.Connect(ipEndPoint);
        }
        catch (Exception e)
        {
            Debug.Log("<<<<<<<"+e);
            return;
        }
        
        dataBuffer = Encoding.UTF8.GetBytes("客户端发送的信息");
        clientSocket.Send(dataBuffer);
        clientSocket.BeginReceive(data, 0, data.Length, SocketFlags.None, ReceiveCallBack, clientSocket);
        //while (true)
        //{
        //    Console.WriteLine("输入数据：");
        //    string s = Console.ReadLine();
        //    //当输入c时，Socket关闭
        //    if (s == "c")
        //    {
        //        clientSocket.Close();
        //        return;
        //    }
        //    dataBuffer = Encoding.UTF8.GetBytes(s);
        //    clientSocket.Send(dataBuffer);
        //}

        //Console.ReadKey();
    }
    private void ReceiveCallBack(IAsyncResult result)
    {
        Socket clientSocket = null;
        clientSocket = result.AsyncState as Socket;
        int length = clientSocket.EndReceive(result);
        string message = Encoding.UTF8.GetString(data, 0, length);
        Debug.Log("收到消息：" + message);
        //重新调用开始接收数据
        clientSocket.BeginReceive(data, 0, data.Length, SocketFlags.None, ReceiveCallBack, clientSocket);
    }
}
